<?php
namespace plugins\order\controller;
use cmf\controller\PluginAdminBaseController;
use think\Db;
use app\common\lib\model_operate\Transit;
use plugins\order\controller\ApiIndexController;
use plugins\order\model\OrderModel;
use plugins\order\model\OrderConsigneeModel;
use plugins\order\model\OrderGoodsListModel;
use plugins\order\model\OrderLogModel;
use plugins\goods\interfaceLib\GoodsClassify;
use plugins\goods\model\GoodsSpecModel;
use plugins\logistics\controller\AdminIndexController as logistics;
use plugins\order\model\OrderMemberModel;
use plugins\address\model\AddressModel;
use plugins\logistics\model\LogisticsModel;
use plugins\store\model\StoreModel;
use plugins\pay\lib\Pay;	//支付接口
use plugins\logistics\controller\LogisticsKdniaoController;
class AdminIndexController extends PluginAdminBaseController
{
	//订单首页
	public function index()
	{
		//订单过期检查
		( new OrderMemberModel )->overTimeOrderCheck();		
		$param = $this->request->param();
		$search =  Transit::createTags('search');
		$search->setParam($param);
		$table = Transit::createTags('table');
		$table->setParam($search);
		//权限检测
		$check = ( new \plugins\store\Common )->getAllowAccess();
		if($check === true){
			if(empty($param['store_id'])){
				$where['cmf_order.store_id'] = 'admin';
				$store_id = 'admin';
			}else{
				$where['cmf_order.store_id'] = $param['store_id'];
				$store_id = $param['store_id'];
			}
		}else{
			$where['cmf_order.store_id'] = $check;
			$store_id = $check;
		}
		$pagesize = isset( $param [ 'pagesize' ] ) ? $param [ 'pagesize' ] : 20;
		$param['order_status'] = isset($param['order_status']) ? $param['order_status'] : "";
		$where['cmf_order.order_status'] = ['neq','6'];
		//导出表格
		if(!empty($param['export']) && $param['export'] == 1){
			$list = $table->query()->where($where)->order('id desc')->select();
			$table->export($list);
		}
		//正常页面排序以id
		$order['cmf_order.id'] = 'desc';
		//已发货页面时排序以发货时间
		if($param['order_status'] == 3){
			$order = [];	
			$order['cmf_logistics_order.delivery_time'] = 'desc';
		}
		
		$list = $table
				->query()
				->where($where)
				->order($order)
				->paginates($pagesize,false,['query'=>$param]);
		$this->assign('search',$search);
		//1
		$this->assign('table',$table);
		$this->assign('searchStr',$search->createHtml());
		//2
		$this->assign("list",$list);
		/** 订单数量统计 **/
		$OrderModel = new OrderModel;
		//count
		$count = $OrderModel->where(['store_id'=>$store_id])->count();
		//待付款count	1
		$count1 = $OrderModel->where(['order_status'=>1,'store_id'=>$store_id])->count();
		//待发货count	2
		$count2 = $OrderModel->where(['order_status'=>2,'store_id'=>$store_id])->count();
		//已发货count	3
		$count3 = $OrderModel->where(['order_status'=>3,'store_id'=>$store_id])->count();
		//已完成count	4
		$count4 = $OrderModel->where(['order_status'=>4,'store_id'=>$store_id])->count();
		//已关闭count	5
		$count5 = $OrderModel->where(['order_status'=>5,'store_id'=>$store_id])->count();
		$this->assign('order_status',$param['order_status']);
		$this->assign('count',$count);
		$this->assign('count1',$count1);
		$this->assign('count2',$count2);
		$this->assign('count3',$count3);
		$this->assign('count4',$count4);
		$this->assign('count5',$count5);
		return $this->fetch();
	}
	//订单详情
	public function orderDetail()
	{
		$param = $this->request->param();
		//订单信息
		$detail = Transit::createTags('detail');
		$order = $detail->query()->where(['order_num'=>$param['order_num']])->find();
		//强制更改支付状态
		if($order['order_status'] == 1){
			$order['money_type'] = '';
		}
		$order_html = $detail->createTableHtml($order,3);
		$this->assign('order_html',$order_html);
		$this->order_consignee($param);		//收货人信息
		$this->order_goods_list($param);	//商品列表
		$this->order_log($param);	//日志
		//订单信息
		$order = ( new OrderModel )->get(['order_num'=>$param['order_num']]);
		//订单商品信息
		$order_goods_list = ( new OrderGoodsListModel )->all(['order_num'=>$param['order_num']]);
		//订单日志
		// $order_log = ( new OrderLogModel )->order('log_time','desc')->where(['order_num'=>$param['order_num']])->select();
		$this->assign('order',$order);
		$this->assign('order_goods_list',$order_goods_list);
		// $this->assign('order_log',$order_log);
		return $this->fetch();
	}
	//	订单收货人信息
	private function order_consignee($param)
	{
		$detail = Transit::createTags('detail');
		//收货人信息
		$order_consignee = $detail->query()->where(['order_num'=>$param['order_num']])->find();
		$order_consignee_html = $detail->createTableHtml($order_consignee,2);
		$this->assign('order_consignee_html',$order_consignee_html);
	}
	//订单商品列表
	private function order_goods_list($param)
	{
		$search =  Transit::createTags('search');
		$search->setParam($param);
		$goods_table = Transit::createTags('table');
		$goods_table->setParam($search);
		$goods = $goods_table->query()->where(['order_num'=>$param['order_num']])->select();
		$this->assign('goods',$goods);
		$this->assign('goods_table',$goods_table);
	}
	//订单日志
	private function order_log($param)
	{
		$search =  Transit::createTags('search');
		$search->setParam($param);
		$log_table = Transit::createTags('table');
		$log_table->setParam($search);
		if(empty($param['page'])){
			$param['page'] = 1;
		}
		$log = $log_table->query()->where(['order_num'=>$param['order_num']])->order('log_time desc')
				->paginates(10,false,['page'=>$param['page']]);
		$this->assign('log',$log);
		$this->assign('log_table',$log_table);
	}
	//修改收货人信息 21
	public function consigneeEdit()
	{
		$address = new AddressModel;
		//地址列表
		$address_list = $address->getAddress();
		if($this->request->isGet()){
			$get = $this->request->get();
			//收货人信息
			$order_consignee = ( new OrderConsigneeModel )->get(['order_num'=>$get['order_num']]);
			$order_consignee->order_consignee_address = json_decode($order_consignee->order_consignee_address);

			$arr = [];
			foreach ($order_consignee->order_consignee_address as $key => $value) {
				$arr[] = $key;
			}
			$list = [];
			$list['provice'] = 0;
			$list['city'] = 0;
			$list['district'] = 0;
			//省
			foreach ($address_list as $key => $value) {
				if($value['value'] == $arr[0]){
					$list['provice'] = $key;
					break;
				}
			}
			//市
			foreach ($address_list[$list['provice']]['children'] as $key => $value) {
				if($value['value'] == $arr[1]){
					$list['city'] = $key;
					break;
				}
			}
			//区
			foreach ($address_list[$list['provice']]['children'][$list['city']]['children'] as $key => $value) {
				if($value['value'] == $arr[2]){
					$list['district'] = $key;
					break;
				}
			}
			$this->assign('list',$list);
			$address_list = json_encode($address_list);
			$this->assign('address_list',$address_list);
			$this->assign('order_consignee',$order_consignee);
			return $this->fetch();
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			checkParam(['provice'=>['message'=>'省份不能为空'],'city'=>['message'=>'城市不能为空'],'district'=>['message'=>'区不能为空']],$post);
			$arr[$address_list[$post['provice']]['value']] = $address_list[$post['provice']]['label'];
			$arr[$address_list[$post['provice']]['children'][$post['city']]['value']] = $address_list[$post['provice']]['children'][$post['city']]['label'];
			$arr[$address_list[$post['provice']]['children'][$post['city']]['children'][$post['district']]['value']] = $address_list[$post['provice']]['children'][$post['city']]['children'][$post['district']]['label'];
			$post['order_address'] = $address_list[$post['provice']]['label'] . $address_list[$post['provice']]['children'][$post['city']]['label'] . $address_list[$post['provice']]['children'][$post['city']]['children'][$post['district']]['label'];
			$post['order_consignee_address'] = json_encode($arr);
			$return = ( new OrderConsigneeModel )->allowField(true)->save($post,['order_num'=>$post['order_num']]);
			if($return){
				( new OrderLogModel )->createLog(21,$post['order_num']);
				return $this->success('修改成功');
			}
			return $this->error('修改失败');
		}
	}

	//修改费用信息
	public function moneyEdit()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			//订单信息
			$order = ( new OrderModel )->get(['order_num'=>$get['order_num']]);
			//收货人信息
			$order_consignee = ( new OrderConsigneeModel )->get(['order_num'=>$get['order_num']]);
			//订单商品信息
			$order_goods_list = ( new OrderGoodsListModel )->all(['order_num'=>$get['order_num']]);
			$this->assign('order',$order);
			$this->assign('order_consignee',$order_consignee);
			$this->assign('order_goods_list',$order_goods_list);
			return $this->fetch();
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$return1 = ( new OrderModel )->where(['order_num'=>$post['order_num']])->update(['order_money'=>$post['order_money']]);
			$return2 = ( new OrderConsigneeModel )->where(['order_num'=>$post['order_num']])->update(['order_consignee_money'=>$post['order_consignee_money']]);
			if($return1 || $return2){
				( new OrderLogModel )->createLog(22,$post['order_num']);
				return $this->success('修改成功');
			}
			return $this->error('修改失败');
		}
	}

	//关闭订单 ajax
	public function orderClose()
	{
		$post = $this->request->post();
		$return = ( new OrderModel )->where(['order_num'=>$post['id']])->update(['order_status'=>5]);
		if($return){
			( new OrderLogModel )->createLog(32,$post['id']);
			return $this->success('订单已关闭');
		}
		return $this->error('操作失败');
	}

	//取消订单
	public function orderCancel()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			return $this->fetch();
		}
		if($this->request->isPost()){
		}
	}
	//订单跟踪
	public function orderTrace()
	{
		$param = $this->request->param();
		$logistic = db('logistics_order')->where(['order_num'=>$param['order_num']])->find();
		if($logistic['code'] == '' && $logistic['logistics_code'] == NULL){
			echo '当前无物流信息，请稍后查看';
			exit();
		} 
	  // $logistic["code"] = "YTO";
	  // $logistic["logistics_code"] = "YT5026639237826";
		$this->redirect(cmf_plugin_url('Logistics://LogisticsKdniao/index')."?".http_build_query(['ShipperCode'=>$logistic['code'],'LogisticCode'=>$logistic['logistics_code'],'search'=>true]));
	}
	//发送站内信
	public function message()
	{
	}
	//删除订单
	//备注订单
	public function orderRemark()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$this->assign('order_num',$get['order_num']);
			return $this->fetch();
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			$return = ( new OrderLogModel )->createLog(31,$post['order_num'],$post['remark']);
			if($return){
				return $this->success('添加完成');
			}else{
				return $this->error('添加失败');
			}
		}
	}
	//修改订单商品列表
	public function orderGoodsEdit()
	{
		if($this->request->isGet()){
			$get = $this->request->get();
			$this->assign('order_num',$get['order_num']);
			//订单商品信息
			$order_goods_list = ( new OrderGoodsListModel )->all(['order_num'=>$get['order_num']]);
			$this->assign('order_goods_list',$order_goods_list);
			//权限检测
			$check = ( new \plugins\store\Common )->getAllowAccess();
			if($check === true){
				$where = '';
			}else{
				$where = ['store_id'=>$check];
			}
			$list = db('goods')->field('id,goods_name')->where($where)->select()->toArray();
			$this->assign('list',$list);
			return $this->fetch();
		}
		if($this->request->isPost()){
			$post = $this->request->post();
			( new OrderGoodsListModel )->saveAll($post['data']);
			return $this->success('修改完成');
		}
	}
	//获得商品信息
	public function getGood()
	{
		$get = $this->request->post();
		$where = 1;
		$where .= ' and id = '.$get['id'];
		$info = db('goods')->where(['id'=>$get['id']])->find();
		//格式化分类
		$info['cat'] = ( new GoodsClassify )->pidname($info['catid']);
		//规格选项生成
		$spec = db('goods_spec')->where(['cid'=>$info['catid']])->find();
		$cat = new GoodsSpecModel;
		$cat->setinfo($spec['spec_id']);
		$result = $cat->info;
		//后台生成的html代码
		$html = '';
		// <select name="city" lay-verify="">
		//   <option value="">请选择一个城市</option>
		//   <option value="010">北京</option>
		//   <option value="021">上海</option>
		//   <option value="0571">杭州</option>
		// </select>
		$spec_arr = [];
		foreach ($result['name'] as $key => $value) {
			$html .= $value['spec_name'].":";
			$html .= "<select name='".$value['name_id']."' lay-verify='' class='choose'>";
				foreach ($value['attr'] as $k => $v) {
					if(empty($spec_arr[$key])){
						$spec_arr[$key] = $v['attr_id'];
					}
					$html .= "<option value='".$v['attr_id']."'>".$v['attr_name']."</option>";
				}
			$html .= "</select>";
		}

		$info['spec'] = $html;
		return $info;
	}
	//订单添加商品
	public function orderAddGoods()
	{
		$post = $this->request->post();
	}
	//订单发货
	public function send()
	{
		$data = $this->request->post();
		if(is_string($data['order_num'])){
			$list[0] = $data['order_num'];
		}else{
			$list = $data['order_num'];
		}
		
		$logist = new LogisticsModel;
	    //开启事务操作
	    Db::startTrans();
	    try{
			foreach ($list as $key => $value) {
				//订单详情
				$order = ( new OrderModel )->get(['order_num'=>$value]);
				$store_id = $order->store_id;
				$store = ( new StoreModel )->get(['store_id'=>$store_id]);
				//订单收货人
				$order_consignee = ( new OrderConsigneeModel )->get(['order_num'=>$value]);
				$address = json_decode($order_consignee->order_consignee_address,true);
				//订单商品列表
				$order_goods_list = ( new OrderGoodsListModel )->all(['order_num'=>$value]);
				$data['order_time'] = $order->paytime;
				$data['order_num'] = $order->order_num;
				$data['store_id'] = $order->store_id;
				$data['name'] = $order_consignee->order_consignee_name;
				$data['mobile'] = $order_consignee->order_consignee_phone;
				$data['province'] = array_shift($address);
				$data['city'] = array_shift($address);
				$data['area'] = array_shift($address);
				$data['address'] = $order_consignee->order_address_detail;
				$data['remarks'] = $order->remark;
				$data['goods'] = '';
				foreach ($order_goods_list as $k => $v) {
					$data['goods'] .= $v->order_goods_name.",";
				}
				$data['goods'] = trim($data['goods'],',');

				$data['store_name'] = $store->store_name;
				$result = $logist->deliveryInfo($data);
				// {"status":"success","message":"成功","code":200,"data":""}
				if(!empty($result['status']) && $result['status'] == 'success'){
					//订单状态转为3
					$order->save(['order_status'=>3]);
					Db::commit();
				}else{
					return $this->error($data['order_num'].'操作失败,'.$result);
				}
			}
	    }catch(\Exception $e){
	        // 回滚事务
	        Db::rollback();
	        return $this->error($e->getMessage());
	    }
		return $this->success('发货成功');
	}
}